'use strict'
var fs = require('fs')
var path = require('path')
var mongoose = require('mongoose')
var Admin = mongoose.model('admin')
var Promise = require('bluebird')
var readFileAsync = Promise.promisify(fs.readFile);
var writeFileAsync = Promise.promisify(fs.writeFile);

exports.login = async (ctx, next) => {
  var { account, password } = ctx.request.body;
  if (!account || !password) {
    ctx.body = {
      success: false,
      err: '账户或密码未输入！'
    }
    return next
  }
  var admin = await Admin.findOne({
    account: account,
    password: password
  }).exec()
  if (admin) {
    // ctx.cookies.set('webToken', 'account', { httpOnly: false });
    ctx.body = {
      success: true,
      message: '登录成功',
      account: account,
      avatar: admin.avatar || ''
    }
    ctx.session.user = {
      _id: admin._id
    }
  } else {
    ctx.body = {
      success: false,
      err: '账户或密码错误！'
    }
  }
}
exports.inquire = async (ctx, next) => {
  var page = parseInt(ctx.query.page) || 1
  var count = parseInt(ctx.query.count) || 15
  var offset = (page - 1) * count
  var queryArray = await Admin.find()
      .sort({
        'createAt': -1
      })
      .skip(offset)
      .limit(count);
  var total = await Admin.estimatedDocumentCount()
  ctx.body = {
    success: true,
    datas: queryArray,
    total: total
  }
}
exports.add = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var account = await Admin.findOne({account: body.account})
    if(account){
      ctx.body = {
        success: false,
        message: '账户已存在'
      }
      return;
    }
    var data = new Admin({ account: body.account, password: body.password, role: body.role, status: body.status });
    data.save();
    ctx.body = {
      success: true,
      message: '创建成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.update = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var msg = await Admin.findByIdAndUpdate(body._id, { account: body.account, password: body.password, role: body.role, status: body.status })
    ctx.body = {
      success: true,
      message: '编辑成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.remove = async (ctx, next) => {
  try {
    var id = ctx.query && ctx.query.id
    if(id) {
      var admin = await Admin.findById(id);
      if(admin.account !== 'admin') {
        var msg = Admin.findOneAndRemove({_id: id}).exec();
        if(msg){
          ctx.body = {
            success: true,
            message: '删除成功'
          }
        }else{
          ctx.body = {
            success: false,
            message: '没有该用户！'
          }
        }
      }else {
        ctx.body = {
          success: false,
          message: '该用户不能被删除！'
        }
      }
    }
  } catch (error) {
    console.log('删除失败');
  }
}
exports.logout = async (ctx, next) => {
  try {
    // console.log(ctx.cookies.get('SESSIONID'));
    // ctx.cookies.set('SESSIONID', {expires: Date.now('2000-01-01')});
    ctx.session = {}
    ctx.body = {
      success: true,
      message: '退出成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.updateAvatar = async (ctx, next) => {
  let imgName = ctx.request.files.avatar.name;
  let imgPath = ctx.request.files.avatar.path;
  var des_file = process.cwd() + "/public/uploads/"+imgName;
  console.log(des_file);
  try {
    console.log(imgPath);
    // 图片上传进来后,被保存在内存路径中（个人理解，很重要，姑且这样理解）;
    let data = await readFileAsync(imgPath);
    // console.log(data);
    let exec = await writeFileAsync(des_file, data);
    // console.log(exec);
    if( exec ){
      console.log( exec );
      ctx.body = {
        success: false,
        message: '修改失败'
      }
    }else{
      let avatarUrl = 'http://localhost:6789/uploads/'+imgName+'?tiem='+new Date().getTime();
      var msg = await Admin.findByIdAndUpdate(ctx.session.user._id, {
        avatar: avatarUrl
      });
      ctx.body = {
        success: true,
        message: '修改成功',
        url: avatarUrl
      }
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}